package com.etoak.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.etoak.common.core.exception.CustomException;
import com.etoak.common.core.properties.ImageProperties;
import com.etoak.common.core.vo.PageVO;
import com.etoak.entity.Dishes;
import com.etoak.mapper.DishesMapper;
import com.etoak.service.DishesService;
import com.etoak.vo.DishesVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.List;

/**
 * 服务实现类
 *
 * @author etoak
 * @since 2025-07-28
 */
@Service
public class DishesServiceImpl extends ServiceImpl<DishesMapper, Dishes> implements DishesService {

    @Autowired
    ImageProperties imageProperties;

    @Override
    public void add(Dishes dishes) {
        if (ObjectUtils.isNotEmpty(getByName(dishes.getName()))) {
            throw new CustomException("菜品名称重复");
        }

        dishes.setCreateTime(DateUtil.now());

        this.save(dishes);
    }

    @Override
    public PageVO<DishesVO> getList(int pageNum, int pageSize, Dishes dishes) {
        PageHelper.startPage(pageNum, pageSize);
        List<DishesVO> dishesVOList = baseMapper.getList(dishes);
        PageInfo<DishesVO> pageInfo = new PageInfo<>(dishesVOList);
        return new PageVO<>(dishesVOList, pageInfo.getTotal());
    }

    @Override
    public void updateDishes(int id, Dishes dishes) {
        if (ObjectUtils.isEmpty(getById(id))) {
            throw new CustomException("该菜品不存在！");
        }

        String dishesName = dishes.getName();
        if (StringUtils.isNotEmpty(dishesName)) {
            Dishes savedDishes = getByName(dishesName);
            if (ObjectUtils.isNotEmpty(savedDishes) && !savedDishes.getId().equals(id)) {
                throw new CustomException("不能将名称修改为其他菜品的名称！");
            }
        }

        dishes.setId(id);
        dishes.setUpdateTime(DateUtil.now());
        this.updateById(dishes);
    }

    @Override
    public void deleteDishes(int id) {
        Dishes dishes = getById(id);
        // 如果根据 id 查不到数据，则不做删除
        if (ObjectUtils.isEmpty(dishes)) {
            throw new CustomException("食材不存在！");
        }
        String url = dishes.getUrl();
        String fileName = url.substring(url.lastIndexOf("/") + 1);

        File file = new File(imageProperties.getUploadDir(), fileName);
        if (file.exists()) {
            file.delete();
        }

        this.removeById(id);
    }

    @Override
    public List<DishesVO> getByIds(List<Integer> ids) {
        return baseMapper.getByIds(ids);
    }

    private Dishes getByName(String name) {
        return lambdaQuery().eq(Dishes::getName, name).one();
    }
}
